import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {RolesService} from "../roles.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {AccountsService} from "../../accounts/accounts.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../models/msg-result";
import {Account} from "../../accounts/account";
import {MsgConstants} from "../../../../constants/constants";

declare  var $;

@Component({
  selector: 'app-role-assign-user',
  templateUrl: './role-assign-user.component.html'
})
export class RoleAssignUserComponent implements OnInit {
  /**
   * 声明路由id变量
   */
  accountId :string;

  account :Account;

  /**
   * 定义id
   */
  roleId :string;

  /**
   *
   * @type {Array}
   */
  accountIds : Array<string>= [ ];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private rolesService: RolesService,
    private dialogService: OneDialogService,
    private accountsService: AccountsService
  ) {
    this.initObject();
  }

  ngOnInit() {
    //异步调用
    this.pushPage();

    //获取路由数据
    if (!!this.route.snapshot.params["roleId"]) {
      this.roleId = this.route.snapshot.params["roleId"];
      //获取账户数据进行初始化
      this.initRoleFormData(this.roleId);
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("角色管理", "分配账户", path);
  }

  /**
   * 初始化没有分配该角色的账户
   */
  initRoleFormData(roleId) {
    this.accountsService.getUndistributionRoleAccount(roleId).subscribe(
      result => this.responseUtil.success(result, this.processRoleInitFormDataResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 截取初始化账户数据
   * @param result
   */
  private processRoleInitFormDataResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      for (let account of result.data) {
        $("#select_option_html").append("<option id=" + account.id + " value=" + account.id + ">" + account.accountName + "</option>");
      }
      this.getAssiAccountByRoleId(this.roleId);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取某角色已分配的账户
   * @param roleId
   */
  getAssiAccountByRoleId(id) {
    this.rolesService.getAssignedAccount(id).subscribe(
      result => this.responseUtil.success(result,this.processAssignedAccResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   *
   * @param result
   */
  private processAssignedAccResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      for (let account of result.data) {
        $("#select_option_html").append("<option id=" + account.id + " selected='selected' value=" + account.id + ">" + account.accountName + "</option>");
      }
      this.initAssigeRoleForm();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 保存分配角色的账户
   */
  saveAssiAccount() {
    if (!!this.roleId && !!this.accountIds) {
      this.rolesService.assignAccount(this.roleId, this.accountIds).subscribe(
        result => this.responseUtil.success(result, this.processAssiAccountResult),
        error => this.responseUtil.error(error)
      );
    } else {
      this.dialogService.modalInfo("账户或角色为空！", this.cancelAssiAccount);
    }
  }

  /**
   * 保存成功后调用
   * @param json
   */
  private processAssiAccountResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelAssiAccount());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消按钮
   */
  cancelAssiAccount = () => {
    this.router.navigate(['..'], {relativeTo: this.route});
  }


  /**
   * 实例化对象
   */
  private initObject() {
    this.account =new Account("","","","","","","","","","0","0","0","0","0");
  }

  /**
   *
   */
  initAssigeRoleForm() {
    //分配权限
    var demo2 = $('.demo1').bootstrapDualListbox({
      nonSelectedListLabel: '未分配账户',
      selectedListLabel: '已分配账户',
      preserveSelectionOnMove: 'moved',
      moveAllLabel: "移动所有",
      removeAllLabel: "移除所有",
      infoText: " ",
      infoTextEmpty: " ",
      filterPlaceHolder: "请输入要搜索的内容",
      moveOnSelect: true
    });

    /**
     *
     */
    $(".moveall").html('<i class="glyphicon glyphicon-chevron-right"></i><i class="glyphicon glyphicon-chevron-right"></i> ');

    $(".removeall").html('<i class="glyphicon glyphicon-chevron-left"></i><i class="glyphicon glyphicon-chevron-left"></i> ');

    /**
     * 分页
     */
    // $(".bootstrap-duallistbox-container>div").each(function () {
    //   $(this).append(`
    //         <ul class="pagingDetail pull-left" style="margin-top: 5px;">
    //             <li><a href="#">共<span>10</span>条 每页：<span>10</span>条</a></li>
    //         </ul>
    //         <ul class="pagination pull-right" style="margin-top: 5px;">
    //             <li><a href="#">上一页</a></li>
    //             <li><a href="#">下一页</a></li>
    //         </ul>`
    //   )
    // });

    /**
     *取消移除所有按钮
     */
    $(".one-duallistbox-container .btn-group").html("");

    /**
     *左侧列表框的右移
     */
    $("[name=accountName_helper1]").change(function () {
      this.options = $('#bootstrap-duallistbox-selected-list_accountName option').map(
        function (index, item) {
          return $(item).val();
        });
      this.accountIds = this.options.toArray();
    }.bind(this));

    /**
     *右侧列表框的左移
     */
    $("[name=accountName_helper2]").change(function () {
      this.options = $('#bootstrap-duallistbox-selected-list_accountName option').map(
        function (index, item) {
          return $(item).val();
        });
      this.accountIds = this.options.toArray();
    }.bind(this));
  }
}
